﻿#include "sys.h"

void System_Reset(void)
{
    __set_FAULTMASK(1);
    HAL_NVIC_SystemReset();
}

void HAL_Delay_us(__IO uint32_t delay)
{
    int last, curr, val;
    int temp;
    while (delay != 0)
    {
        temp = delay > 900 ? 900 : delay;
        last = SysTick->VAL;
        curr = last - CPU_FREQUENCY_HZ * temp;
        if (curr >= 0)
        {
            do
            {
                val = SysTick->VAL;
            } while ((val < last) && (val >= curr));
        }
        else
        {
            curr += CPU_FREQUENCY_HZ * 1000;
            do
            {
                val = SysTick->VAL;
            } while ((val <= last) || (val > curr));
        }
        delay -= temp;
    }
}

uint8_t ADD8_Calculation(uint8_t *array, uint16_t size)
{
    uint8_t i, add = 0;
    for (i = 0; i < size; i++)
    {
        add += array[i];
    }
    array[size] = add;
    return add;
}

uint8_t ADD8_Check(uint8_t *array, uint16_t size)
{
    uint8_t add = 0;
    for (uint8_t i = 0; i < size - 1; i++)
    {
        add += array[i];
    }
    if (add == array[size - 1])
        return 0;
    else
        return 1;
}

uint16_t CRC_Calculation(uint8_t *data, uint16_t size)
{
    uint16_t i, crc = 0xFFFF;

    for (i = 0; i < size; i++)
    {
        crc ^= data[i];
        for (uint8_t j = 0; j < 8; j++)
        {
            if (crc & 0x0001)
            {
                crc >>= 1;
                crc ^= 0xA001;
            }
            else
            {
                crc >>= 1;
            }
        }
    }
    data[size] = crc;
    data[size + 1] = crc >> 8;
    return crc;
}

uint8_t CRC_Check(uint8_t *data, uint16_t size)
{
    uint16_t crc = (uint16_t)data[size - 1] << 8;
    crc |= data[size - 2];

    if (crc == CRC_Calculation(data, size - 2))
        return 0;
    else
        return 1;
}

// RGB888转RGB565格式
uint16_t RGB888ToRGB565(uint32_t color)
{
    uint8_t r = (color >> 16) & 0xFF; // 提取红色通道
    uint8_t g = (color >> 8) & 0xFF;  // 提取绿色通道
    uint8_t b = color & 0xFF;         // 提取蓝色通道

    uint16_t red = (r >> 3) & 0x1F;   // 将红色通道转换为5位
    uint16_t green = (g >> 2) & 0x3F; // 将绿色通道转换为6位
    uint16_t blue = (b >> 3) & 0x1F;  // 将蓝色通道转换为5位

    return (red << 11) | (green << 5) | blue; // 组合成RGB565格式的颜色值
}
